package genedit.controller.interfaceActions;

import genedit.controller.DeleteCommand;
import genedit.gui.GMainFrame;
import genedit.gui.GProjectTree;
import genedit.model.Document;
import genedit.model.HierarchyElement;
import genedit.model.Package;
import genedit.model.Project;
import genedit.model.Workspace;
import genedit.model.graph.GraphDocument;
import genedit.model.graph.GraphElement;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.KeyStroke;

/**
 * Akcija zadužena za uklanjanje čvorova stabla hijerarhije.
 * 
 * @author Nikola
 * @version 1.2 15/12/13
 */
public class GDeleteA extends AbstractAction {
	private static final long serialVersionUID = 1L;

	protected static GDeleteA instance = null;

	protected GDeleteA() {
		putValue(NAME, "Delete");
		putValue(SHORT_DESCRIPTION, "Delete");
		putValue(SMALL_ICON, new ImageIcon("resources/icons/erase.png"));
		putValue(MNEMONIC_KEY, KeyEvent.VK_D);
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
	}

	public static AbstractAction getInstance() {
		if (instance == null)
			instance = new GDeleteA();
		return instance;
	}

	/**
	 * Akcija briše grafičke elemente (putem komande za brisanje), uklanja
	 * dokumente i pakete iz projekta ili zatvara projekat, u zavisnosti od toga
	 * šta je selektovano.
	 */
	public void actionPerformed(ActionEvent arg0) {
		if (GMainFrame.getInstance().getProjectTree().getTree().hasFocus()) {
			Object p = GProjectTree.getInstance().getTree().getLastSelectedPathComponent();

			if (p instanceof Workspace || p == null)
				return;

			if (p instanceof HierarchyElement) {
				if (p instanceof Project)
					GCloseA.getInstance().actionPerformed(arg0);
				else if (p instanceof Package || p instanceof Document) {
					HierarchyElement he = (HierarchyElement) p;
					((HierarchyElement) (he).getParent()).removeChild(he);
					GMainFrame.getInstance().closeViewsOfClosedDocuments((HierarchyElement) p);
				}
			} else if (p instanceof GraphElement) {
				GraphElement element = (GraphElement) p;
				((GraphDocument) element.getParent()).removeElements(element);
				((GraphDocument) element.getParent()).removeSelectedElements(element);
			}
		}

		else {
			if (Workspace.getInstance().getActiveDocument() == null)
				return;
			DeleteCommand dlt = new DeleteCommand(true);
			dlt.setDocument(Workspace.getInstance().getActiveDocument());
			dlt.setDeletedElements(Workspace.getInstance().getActiveDocument().getModel()
					.getSelectedElements());

			Workspace.getInstance().getActiveDocument().getModel().getInvoker().executeCommand(dlt);
		}
	}
}